package dyyx.fastjson;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.DoubleSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;

import dyyx.dto.Pet;

public class FastjsonTest1 {
	public static void main(String[] args) throws Exception {
			System.out.println("hello,FastjsonTest1,"+new Date());
			
			
			SerializeConfig config = SerializeConfig.getGlobalInstance();  
		    config.put(Double.class, new DoubleSerializer("0.##")); 
			
			Pet pet = new Pet("cat",3,new Date());
			pet.setInfo("hello");
			System.out.println(pet);

			String str = JSON.toJSONString(pet);
			System.out.println(str);
			
			JSONObject jsonobj = JSON.parseObject(str);
			System.out.println("jsonobj="+jsonobj);

			// JSONObject extends com.alibaba.fastjson.JSON implements java.util.Map

			
			pet = JSON.parseObject(str, Pet.class);
			System.out.println(pet);

			List<Pet> pets = new ArrayList<Pet>();
			pets.add(pet);
			pet = new Pet("tiger",5,new Date());
			pets.add(pet);

			
			str = JSON.toJSONString(pets);
			System.out.println(str);
			
			JSONArray jsonarr = JSON.parseArray(str);
			System.out.println("jsonarr="+jsonarr);
			
			// 使用 TypeReference
			List<Pet> pets2 = JSON.parseObject(str, new  TypeReference<List<Pet>>(){});
			for(Pet item:pets2){
				System.out.println(item);
			}
			
			// JSONArray extends com.alibaba.fastjson.JSON implements java.util.List
			
			// java.lang.ClassCastException: com.alibaba.fastjson.JSONArray cannot be cast to com.alibaba.fastjson.JSONObject
			// jsonobj = JSON.parseObject(str);
			// System.out.println("jsonobj="+jsonobj);
			
			str = JSON.toJSONString(pets, SerializerFeature.BeanToArray);
			System.out.println(str);


			Map<Integer,String> map = new HashMap<Integer,String>();
			map.put(1, "a");
			map.put(2, "b");
			
			str = JSON.toJSONString(map);
			// {1:"a",2:"b"}
			System.out.println(str);
			
			// js 里 key只能是 string 
			str = JSON.toJSONString(map,SerializerFeature.WriteNonStringKeyAsString);	
			// {"1":"a","2":"b"}
			System.out.println(str);

			
			
			
			
		}
}

